//
//  WaitVerifyOrderViewController.m
//  EastMarket
//
//  Created by 李鹏程 on 16/11/2.
//  Copyright © 2016年 guoguo. All rights reserved.
//

#import "WaitVerifyOrderViewController.h"

@interface WaitVerifyOrderViewController ()

@end

@implementation WaitVerifyOrderViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"待审核订单";
    self.view.backgroundColor = EastMarket_backgroundColor;
    _dataSourceArr = [[NSMutableArray alloc] init];
    _productNameArr = [[NSMutableArray alloc] init];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloadDataAfterOrderOperate:) name:NotificationReloadData object:nil];
    pageIndex = 1;
    [self initOrderListUI];
    [self loadViewOrderList];
    [SVProgressHUD showWithStatus:@"加载中"];
    [SVProgressHUD setDefaultStyle:SVProgressHUDStyleCustom];
    [SVProgressHUD setForegroundColor:EastMarket_MainToneColor];
    [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeClear];
}

- (void)reloadDataAfterOrderOperate: (NSNotification *)notification{
    [NSThread detachNewThreadSelector:@selector(callServerGetOrderList) toTarget:self  withObject:Nil];
}

- (void)initOrderListUI {
    
    CGFloat spacing = 8.0f;
    _tabView = [[UITableView alloc] initWithFrame:CGRectMake(8, spacing, SCREEN_WIDTH - 16, SCREEN_HEIGHT - 16 - TabBarHeight) style:UITableViewStylePlain];
    _tabView.showsVerticalScrollIndicator = false;
    _tabView.delegate = self;
    _tabView.dataSource = self;
    _tabView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    _tabView.backgroundColor = EastMarket_backgroundColor;
    [self setExtraCellLineHidden:_tabView];
    [self.view addSubview:_tabView];
    _tabView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewData)];
    // Enter the refresh status immediately
    //[_tabView.mj_header beginRefreshing];
    _tabView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
}
- (void)loadNewData {
    
    pageIndex = 1;
    [self loadViewOrderList];
}

- (void)loadMoreData {
    
    pageIndex += 1;
    [self loadViewOrderList];
}
// 订单列表请求
- (void)loadViewOrderList {
    
    [NSThread detachNewThreadSelector:@selector(callServerGetOrderList) toTarget:self  withObject:Nil];
}

- (void)callServerGetOrderList {
    
    pageSize = 20;
    NSDictionary *dicOfOrderList = [AppServiceInterface orderList:@"WAIT_VERIFY" page:pageIndex pageSize:pageSize];
    [self performSelectorOnMainThread:@selector(updateOrderList:) withObject:dicOfOrderList waitUntilDone:NO];
}

- (void)updateOrderList:(NSDictionary *)dic {
    
    [SVProgressHUD dismiss];
    if (dic && [[dic objectForKey:@"success"] integerValue] == 1) {
        if ([[[dic objectForKey:@"data"] objectForKey:@"page"] integerValue] == 1) {
            [_dataSourceArr removeAllObjects];
        }
        [_dataSourceArr addObjectsFromArray:[[dic objectForKey:@"data"] objectForKey:@"results"]];
        [_tabView reloadData];
        [_tabView.mj_header endRefreshing];
        [_tabView.mj_footer endRefreshing];
        
        if ([[[dic objectForKey:@"data"] objectForKey:@"total"] intValue] <= [[[dic objectForKey:@"data"] objectForKey:@"pageSize"] intValue] * ([[[dic objectForKey:@"data"] objectForKey:@"page"] intValue])) {
            [_tabView.mj_footer endRefreshingWithNoMoreData];
        }
        
    }
}

#pragma mark -- UITableViewDelegate &  UITableViewDatasource

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (_dataSourceArr.count == 0) {
        
        return 2 + 44 * 4 + 3 + 1;
    }
    NSInteger curRow = [indexPath row];
    NSDictionary *orderDic = [_dataSourceArr objectAtIndex:curRow];
    [_productNameArr removeAllObjects];
    [_productNameArr addObjectsFromArray:[orderDic objectForKey:@"orderItemList"]];
    CGFloat height = ( _productNameArr.count + 1)  / 2 * 44 ;
    return height + 2 + 44 * 3 + 3 + 12;    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return _dataSourceArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *cellIdentifier = @"cell";
    OrderViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    if (cell == nil) {
        cell = [[OrderViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.backgroundColor = EastMarket_backgroundColor;
    NSInteger curRow = [indexPath row];
    NSDictionary *orderDic = [_dataSourceArr objectAtIndex:curRow];
    [_productNameArr removeAllObjects];
    [_productNameArr addObjectsFromArray:[orderDic objectForKey:@"orderItemList"]];
    cell.productNameArr = _productNameArr;
    cell.lblOrderID.text = [NSString stringWithFormat:@"%@", [orderDic objectForKey:@"no"]];
    [cell.btnOrderState setTitle:[NSString stringWithFormat:@"%@", [orderDic objectForKey:@"statusTitle"]] forState:UIControlStateNormal];
//    cell.lblOrderName.text = [NSString stringWithFormat:@"%@", [[[[orderDic objectForKey:@"orderItemList"] objectAtIndex:0] objectForKey:@"item"] objectForKey:@"title"]];
    
    cell.lblOrderNum.text = [NSString stringWithFormat:@"共%ld件商品", [[orderDic objectForKey:@"num"] integerValue]];
    cell.lblOrderTotalPrice.text = [NSString stringWithFormat:@"￥%.2lf", [[orderDic objectForKey:@"totalFee"] floatValue]];
    cell.lblOrderAddTime.text = [NSString stringWithFormat:@"下单时间: %@", [GlobalUnit getDateFormatterByMillisecond:[NSString stringWithFormat:@"%@", [orderDic objectForKey:@"createTime"]]]];
    
    CGFloat border = 1.0f;
    CGFloat lblHeight = 44.0f;
    CGRect rect = cell.collectionView.frame;
    rect.size.height = (cell.productNameArr.count + 1) / 2 * 44;
    cell.collectionView.frame = rect;
    cell.viewOrderNumAndSum.frame = CGRectMake(0, cell.collectionView.frame.origin.y + cell.collectionView.frame.size.height + border, SCREEN_WIDTH, lblHeight);
    cell.viewAddTimeAndPay.frame = CGRectMake(0, cell.viewOrderNumAndSum.frame.origin.y + cell.viewOrderNumAndSum.frame.size.height + border, SCREEN_WIDTH, lblHeight);
    cell.viewSpacing.frame = CGRectMake(0, cell.viewAddTimeAndPay.frame.origin.y + cell.viewAddTimeAndPay.frame.size.height, SCREEN_WIDTH, 12);
    
    //status  订单状态 可选值：WAIT_PAY  WAIT_VERIFY  VERIFIED  WAIT_CANCEL,CANCELED
    if ([[orderDic objectForKey:@"status"] isEqualToString:@"WAIT_PAY"]) {
        cell.btnOrderPay.hidden = NO;
        [cell.btnOrderPay setTitle:@"去支付" forState:UIControlStateNormal];
    } else if ([[orderDic objectForKey:@"status"] isEqualToString:@"WAIT_VERIFY"]) {
        
        cell.btnOrderPay.hidden = YES;
//        [cell.btnOrderPay setTitle:@"取消" forState:UIControlStateNormal];
    } else if ([[orderDic objectForKey:@"status"] isEqualToString:@"VERIFIED"]) {
        
        cell.btnOrderPay.hidden = YES;
//        [cell.btnOrderPay setTitle:@"取消" forState:UIControlStateNormal];
    }else if ([[orderDic objectForKey:@"status"] isEqualToString:@"WAIT_CANCEL"]) {
        
        //        [cell.btnOrderPay setTitle:@"重新下单" forState:UIControlStateNormal];
        cell.btnOrderPay.hidden = YES;
    }else if ([[orderDic objectForKey:@"status"] isEqualToString:@"CANCELED"]) {
        
        cell.btnOrderPay.hidden = YES;
//        [cell.btnOrderPay setTitle:@"重新下单" forState:UIControlStateNormal];
    }
    cell.btnOrderStateClick = ^() {
         debugLog(@"%@", [NSString stringWithFormat:@"%@", [orderDic objectForKey:@"id"]]);
        debugMethod();
        WaitVerifyDetailOrderController *orderDetailVC = [[WaitVerifyDetailOrderController alloc] init];
        orderDetailVC.strReceiverName = [NSString stringWithFormat:@"%@", [orderDic objectForKey:@"receiverName"]];
        orderDetailVC.stRreceiverPhone = [NSString stringWithFormat:@"%@", [orderDic objectForKey:@"receiverPhone"]];
        orderDetailVC.strReceiverAddress = [NSString stringWithFormat:@"%@", [orderDic objectForKey:@"receiverAddress"]];
        
        orderDetailVC.strId = [NSString stringWithFormat:@"%@", [orderDic objectForKey:@"id"]];
        orderDetailVC.strNO = [NSString stringWithFormat:@"%@", [orderDic objectForKey:@"no"]];
        orderDetailVC.strStatusTitle = [NSString stringWithFormat:@"%@", [orderDic objectForKey:@"statusTitle"]];
        orderDetailVC.strSellerName = [NSString stringWithFormat:@"%@", [orderDic objectForKey:@"sellerName"]];
        orderDetailVC.strFromTitle = [NSString stringWithFormat:@"%@", [orderDic objectForKey:@"fromTitle"]];
        
        orderDetailVC.strPayTypeTitle = [NSString stringWithFormat:@"%@", [orderDic objectForKey:@"payTypeTitle"]];
        orderDetailVC.strItemTotalFee = [NSString stringWithFormat:@"%@", [orderDic objectForKey:@"itemTotalFee"]];
        orderDetailVC.strDiscountFee = [NSString stringWithFormat:@"%@", [orderDic objectForKey:@"discountFee"]];
        orderDetailVC.strDelivery = [NSString stringWithFormat:@"%@", [orderDic objectForKey:@"deliveryFee"]];
        orderDetailVC.strTotalFee = [NSString stringWithFormat:@"%@", [orderDic objectForKey:@"totalFee"]];
        
        orderDetailVC.strPaidFee = [NSString stringWithFormat:@"%@", [orderDic objectForKey:@"paidFee"]];
        orderDetailVC.strRefund = [NSString stringWithFormat:@"%@", [orderDic objectForKey:@"refundFee"]];
        
        orderDetailVC.strCreateTime = [NSString stringWithFormat:@"%@", [orderDic objectForKey:@"createTime"]];
        
        orderDetailVC.strOrderStatus = [NSString stringWithFormat:@"%@", [orderDic objectForKey:@"status"]];
        [self.navigationController pushViewController:orderDetailVC animated:true];
    };
    cell.btnOrderPayClick = ^() {
        
        debugMethod();
        debugLog(@"%ld", indexPath.row);
        
    };
    
    return cell;
}

#pragma mark -- UITableView Editing
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    return YES;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        [_dataSourceArr removeObjectAtIndex:indexPath.row];
        // Delete the row from the data source.
        [_tabView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
        [_tabView reloadData];
        //[self totalPrice];
    }
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view.
    }
}

- (CGFloat)getHeightWithString:(NSString *)str width:(CGFloat)width font:(CGFloat)font{
    
    if (str.length == 0) {
        
        return 0;
    }
    CGSize size = [str boundingRectWithSize:CGSizeMake(width, 0)
                                    options:NSStringDrawingUsesLineFragmentOrigin
                                 attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:font]}
                                    context:nil].size;
    return size.height;
}

//多余的空行上不显示分割线
- (void)setExtraCellLineHidden: (UITableView *)tableView{
    UIView *view =[ [UIView alloc]init];
    view.backgroundColor = [UIColor clearColor];
    [tableView setTableFooterView:view];
    [tableView setTableHeaderView:view];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
